<!-- 聊天窗口 -->
<template>
	<view class="">
		<u-navbar :is-back="true" :title="fromId"></u-navbar>

		<scroll-view class="scroll-view" :style="{'height': scrollViewHeight + 'rpx'}" :scroll-y="true"
			:scroll-top="scrollTop" :scroll-with-animation="false">
			<view class="padding30">
				<view class="scroll-view-content bg-white padding20 br16" v-if="enquriyInfo.enquiryPersonName">
					<view class="fw500">客户询价信息</view>
					<view class="flex-center m-t20">
						<image :src="enquriyInfo.enquiryPicture[0]" mode="" class="w-120 h-120 br16 m-r20"></image>
						<view class="flex-bettwen flex1 w100">
							<view class="">
								<view class="fw500">{{enquriyInfo.enquiryPersonName}}</view>
								<view class="fs24 text-overflow3 m-t10">{{enquriyInfo.remark}}</view>
								<view class="price-color m-t10">{{enquriyInfo.number}} <text
										class="color-gray fs24">{{enquriyInfo.unit}}</text> </view>
							</view>
							<u-button size="mini" type="primary">详情</u-button>
						</view>
					</view>
				</view>


				<view class="scroll-view-content" v-for="(item,index) in chatList" :key="index">
					<view class="p-t30 flex" v-if="item.from !== currentUser" id="item-id">
						<image src="../../static/avatar.png" mode="" class="w-100 h-100"></image>
						<view class="m-l20">
							<view class="m-b10">{{item.from}}</view>
							<view class="flex1 bg-white br16 padding20 fs26" style="display: inline-block;">
								{{item.msg}}
							</view>
						</view>
					</view>
					<view class="p-t30 w100 flex" style="justify-content: flex-end;" v-if="item.from == currentUser">
						<view class="m-r20" style="text-align: right;">
							<view class="m-b10">{{item.from}}</view>
							<view class=" bg-white br16 padding20 fs26" style="text-align: left;display: inline-block;">
								{{item.msg}}
							</view>
						</view>
						<image src="../../static/avatar.png" mode="" class="w-100 h-100"></image>
					</view>
				</view>
			</view>
		</scroll-view>




		<view class="footer-box">
			<view class="flex padding30">
				<u-icon name="mic" class="icon-box bg-white br12" @click="scrollTop+0.00001" size="40"></u-icon>
				<input type="text" class="ipt-box" v-model="content" @confirm="sendMsg" confirm-type="send" send-text="发送" />
				<image src="../../static/emoji_fill.png" mode="" class="bg-white image-box"></image>
				<u-icon name="bag-fill" class="icon-box bg-white br12 m-l20" size="40"></u-icon>
				<u-icon name="plus" class="icon-box bg-white br12 m-l20" size="40"></u-icon>
				<!-- <u-icon name="mic" class="icon-box bg-white br12" size="40"></u-icon> -->
			</view>
		</view>



	</view>
	</view>
</template>

<script>
	import imUtil from '../../utils/imUtil';
	let WebIM = require("../../utils/WebIM")["default"];
	export default {
		data() {
			return {
				fromInfo: {},
				fromId: '',
				chatList: [],
				currentUser: '',
				content: '',
				scrollTop: 0,
				scrollViewHeight: 0,
				params: {
					cursor: -1,
					pageSize: 50
				},
				enquriyInfo: {
					enquiryPersonName: '',
					enquiryPicture: []
				}, // 询价信息
			}
		},
		onLoad(options) {
			// 报价信息
			if (options.enquriyInfo) {
				console.log('商家报价信息', JSON.parse(decodeURIComponent(options.enquriyInfo)));
				this.enquriyInfo = JSON.parse(decodeURIComponent(options.enquriyInfo))
			}
		},
		mounted() {
			// 取头部高度信息

			let e = uni.getSystemInfoSync()
			let customBar = e.statusBarHeight + 45

			setTimeout(() => {
				uni.createSelectorQuery().in(this).select('.footer-box').boundingClientRect(rect => {
					console.log('底部高度', rect)
					this.scrollViewHeight = (e.windowHeight - customBar - rect.height) * 2
				}).exec();
			}, 1000)



			let imToken = uni.getStorageSync('imToken')
			let imUserName = uni.getStorageSync('imUserName')
			imUtil.loginImBytoken(imUserName, imToken)
			this.currentUser = imUserName

			console.log('路径参数', this.$scope.options.data);
			this.fromId = this.$scope.options.data
			this.getHistoryMsg()
			let that = this

			WebIM.conn.listen({
				// 当前用户收到文本消息。
				onTextMessage: function(message) {
					console.log('收到消息了', message);
					setTimeout(() => {
						that.getHistoryMsg()
						that.channelAck()
					}, 1000)
					// uni.showToast({
					// 	title: '收到消息了'
					// })
				},
			})

			// this.isRead(imUserName)
			this.channelAck()
		},
		methods: {
			// 询价订单
			goEnquriy() {
				uni.navigateTo({
					url: `/pages/opportunity/enquiry-detail?enquiryId=${this.enquriyInfo.enquiryId}`
				})
			},
			
			chatScroll() {
				this.$nextTick(() => {
					uni.createSelectorQuery().in(this).select('.scroll-view-content').boundingClientRect(rect => {
						console.log('rect', rect);
						if (this.chatList.length !== 0) {
							let top = rect.height * this.chatList.length - (this.scrollViewHeight / 2);

							if (top > 0) {
								this.scrollTop = top * 2;
								console.log('scrollTop', this.scrollTop);
							}
						}

					}).exec();
				})

			},

			// 会话标记
			// markConversations(conversationId){
			// 	const options = {
			// 	  conversations: [
			// 	    {conversationId: conversationId, conversationType: 'singleChat'},
			// 	  ],
			// 	  mark: 0,
			// 	}

			// 	WebIM.conn.addConversationMark(options).then(() => {
			// 	  console.log('会话标记成功')
			// 	})
			// },

			// 消息已读回执
			isRead(imUserName) {
				let option = {
					type: "read", // 消息是否已读。
					chatType: "singleChat", // 会话类型，这里为单聊。
					to: this.fromId, // 消息接收方的用户 ID。
					id: imUserName, // 需要发送已读回执的消息 ID。
				};
				let msg = WebIM.message.create(option);
				WebIM.conn.send(msg);
			},

			// 取历史消息
			getHistoryMsg() {
				let that = this
				let options = {
					// 对方的用户 ID 或者群组 ID 或聊天室 ID。
					targetId: this.fromId,
					// 每页期望获取的消息条数。取值范围为 [1,50]，默认值为 20。
					pageSize: this.params.pageSize,
					// 查询的起始消息 ID。若该参数设置为 `-1`、`null` 或空字符串，从最新消息开始。
					cursor: this.params.cursor,
					// 会话类型：（默认） `singleChat`：单聊；`groupChat`：群聊；`chatRoom`：聊天室
					chatType: "singleChat",
					// 消息搜索方向：（默认）`up`：按服务器收到消息的时间的逆序获取；`down`：按服务器收到消息的时间的正序获取。
					searchDirection: "down",
				};
				WebIM.conn
					.getHistoryMessages(options)
					.then((res) => {
						// 成功获取历史消息。
						console.log('获取历史消息', res);
						that.chatList = res.messages
						if (res.messages.length == 50) {
							that.params.cursor = res.messages[res.messages.length - 1].id
							that.getHistoryMsg()
						} else {
							that.chatScroll()
						}

					})
					.catch((e) => {
						console.log('错误了', e);
						// 获取失败。
					});
			},
			// 发送消息
			sendMsg() {
				let that = this
				let option = {
					chatType: 'singleChat', // 会话类型，设置为单聊。
					type: 'txt', // 消息类型。
					to: this.fromId, // 消息接收方（用户 ID)。
					msg: this.content // 消息内容。
				}
				let msg = WebIM.message.create(option);
				WebIM.conn.send(msg).then(() => {
					console.log('消息发送成功');
					that.content = ''
					setTimeout(() => {
						that.getHistoryMsg()
					}, 1000)

				}).catch((e) => {

					console.log("消息发送失败", e);
				})
			},
			// 消息已读回执
			channelAck() {
				let option = {
					chatType: "singleChat", // 会话类型，设置为单聊。
					type: "channel", // 消息类型。固定参数固定值，不要动它
					to: this.fromId, // 接收消息对象（用户 ID)。
				};
				let msg = WebIM.message.create(option);
				WebIM.conn
					.send(msg)
					.then((res) => {
						console.log("%c>>>>>>>>会话已读回执发送成功", "color:#6ad1c7", res);
					})
					.catch((e) => {
						console.log("%c>>>>>>>>>会话已读回执发送失败", "color:#ef8784", e);
					});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.footer-box {
		position: fixed;
		bottom: 0;
		padding-bottom: env(safe-area-inset-bottom);
		width: 100%;
	}

	.icon-box {
		padding: 20rpx;
	}

	.ipt-box {
		width: 280rpx;
		background: #fff;
		border-radius: 12rpx 0rpx 0rpx 12rpx;
		margin-left: 20rpx;
		padding: 18rpx;
	}

	.image-box {
		width: 40rpx;
		height: 40rpx;
		padding: 20rpx;
		border-radius: 0rpx 12rpx 12rpx 0rpx;
	}
</style>
<style>
	page {
		height: 100vh;
		background: #f2f2f2;
	}
</style>